package info.thereisonlywe.onenesspathfinder.ui;

import info.thereisonlywe.core.font.FontLibrary;
import info.thereisonlywe.core.project.ProjectConstants;
import info.thereisonlywe.core.project.ProjectLocalization;
import info.thereisonlywe.core.toolkit.StringToolkit;
import info.thereisonlywe.core.ui.swing.extensions.CustomPanel;
import info.thereisonlywe.core.ui.swing.extensions.table.EmptyCellEditor;
import info.thereisonlywe.core.ui.swing.extensions.table.TextAreaRenderer;
import info.thereisonlywe.onenesspathfinder.controllers.RecitationController;
import info.thereisonlywe.onenesspathfinder.launcher.Main;
import info.thereisonlywe.quran.Quran;
import info.thereisonlywe.quran.text.QuranicText;
import info.thereisonlywe.quran.text.QuranicTextList;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.ToolTipManager;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class VersePane extends JScrollPane {

	private final JTable table_BrowserPane = new JTable()
	{
		@Override
		public void changeSelection(int rowIndex, int columnIndex,
				boolean toggle, boolean extend)
		{

		}

		@Override
		public TableCellRenderer getCellRenderer(int row, int column)
		{
			return getColumnModel().getColumn(0).getCellRenderer();
		}

	};

	private String[] tableValues = new String[] { "" };

	private final JPopupMenu popupMenu_Browser = new JPopupMenu();

	private MouseEvent mouseEvent;

	public VersePane()
	{
		super();
		initComponents();
		initPopupItems();
		initListeners();
	}

	public JTable getTable()
	{
		return table_BrowserPane;
	}

	private void initComponents()
	{
		this.getVerticalScrollBar().setUnitIncrement(12);
		table_BrowserPane.setTableHeader(null);
		table_BrowserPane.setForeground(Color.black);
		table_BrowserPane.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table_BrowserPane.setSelectionBackground(Color.white);
		table_BrowserPane.setSelectionForeground(Color.black);
		TableModel model = new TableModel();
		model.addTableModelListener(new TableListener());
		table_BrowserPane.setModel(model);
		table_BrowserPane.getColumnModel().getColumn(0)
				.setCellRenderer(new TableRenderer());
		table_BrowserPane.getColumnModel().getColumn(0)
				.setCellEditor(new EmptyCellEditor());
		setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.DARK_GRAY));
		ToolTipManager.sharedInstance().unregisterComponent(table_BrowserPane);
		JPanel panel = new JPanel();
		JPanel innerPanel = new CustomPanel(Color.DARK_GRAY);
		innerPanel.setPreferredSize(new Dimension(2, 10));
		JPanel innerPanel2 = new CustomPanel(Color.DARK_GRAY);
		innerPanel2.setPreferredSize(new Dimension(5, 10));
		panel.setLayout(new BorderLayout());
		panel.add(innerPanel, BorderLayout.WEST);
		panel.add(innerPanel2, BorderLayout.EAST);
		panel.add(table_BrowserPane, BorderLayout.CENTER);
		setViewportView(panel);
	}

	private void initPopupItems()
	{

		JMenuItem item;

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "Copy"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				CopyDialog.showDialog(table_BrowserPane.rowAtPoint(mouseEvent
						.getPoint()));
			}
		});
		popupMenu_Browser.add(item);

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.ONENESS_PATHFINDER_PROJECT, "SelectiveCopy"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				SelectiveCopyDialog.showDialog(table_BrowserPane
						.rowAtPoint(mouseEvent.getPoint()));
			}
		});
		popupMenu_Browser.add(item);
		popupMenu_Browser.addSeparator();
		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.ONENESS_PATHFINDER_PROJECT, "AddToBookmarks"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				UIDelegate.BookmarkPaneHook.addBookmarkWindow();
			}
		});
		popupMenu_Browser.add(item);
		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.ONENESS_PATHFINDER_PROJECT,
				"BrowseSimilarVerses"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				SimilarVersesDialog.showDialog();
			}
		});
		popupMenu_Browser.add(item);
		popupMenu_Browser.addSeparator();
		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.ONENESS_PATHFINDER_PROJECT, "GoToVerse"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				GoToVerseDialog.showDialog();
			}
		});
		popupMenu_Browser.add(item);
		popupMenu_Browser.addSeparator();

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.ONENESS_PATHFINDER_PROJECT, "TextManagement"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				TextConfigurationDialog.showDialog();
			}
		});
		popupMenu_Browser.add(item);
		popupMenu_Browser.addSeparator();

		item = new JMenuItem(
				"+ "
						+ ProjectLocalization.getString(
								ProjectConstants.ONENESS_PATHFINDER_PROJECT,
								"FontSize"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				if (UIDelegate.fontSize < 5) UIDelegate.fontSize++;
			}
		});
		popupMenu_Browser.add(item);

		item = new JMenuItem(
				"- "
						+ ProjectLocalization.getString(
								ProjectConstants.ONENESS_PATHFINDER_PROJECT,
								"FontSize"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				if (UIDelegate.fontSize > 0) UIDelegate.fontSize--;
			}
		});
		popupMenu_Browser.add(item);
		popupMenu_Browser.addSeparator();

		JMenu item2;
		JRadioButtonMenuItem item3;
		ButtonGroup bg = new ButtonGroup();

		item2 = new JMenu(ProjectLocalization.getString(
				ProjectConstants.QURAN_PROJECT, "Mushaf"));
		item2.setMargin(UIConstants.MARGIN);

		item3 = new JRadioButtonMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "Simplified"));
		item3.setMargin(UIConstants.MARGIN);
		if (Main.runtimeSettings.getStringAsInt("mushaf") == 0)
			item3.setSelected(true);
		item3.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				Quran.setMushaf(0);
				UIDelegate.refreshVerse();
				UIDelegate.SectionPaneHook.refresh();
				if (QuranicTextList.getPreferred() < 0
						&& MainFrame.view_Windows.isSearchContainerMounted())
				{
					MainFrame.view_Windows.getSearchPanel().refreshResults();
				}
			}
		});

		item2.add(item3);
		bg.add(item3);

		item3 = new JRadioButtonMenuItem(ProjectLocalization.getString(
				ProjectConstants.QURAN_PROJECT, "Uthmani"));
		item3.setMargin(UIConstants.MARGIN);
		if (Main.runtimeSettings.getStringAsInt("mushaf") == 1)
			item3.setSelected(true);
		item3.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				Quran.setMushaf(1);
				UIDelegate.refreshVerse();
				UIDelegate.SectionPaneHook.refresh();
				if (QuranicTextList.getPreferred() < 0
						&& MainFrame.view_Windows.isSearchContainerMounted())
				{
					MainFrame.view_Windows.getSearchPanel().refreshResults();
				}
			}
		});

		item2.add(item3);
		bg.add(item3);

		item3 = new JRadioButtonMenuItem(ProjectLocalization.getString(
				ProjectConstants.QURAN_PROJECT, "Literal.English"));
		item3.setMargin(UIConstants.MARGIN);
		if (Main.runtimeSettings.getStringAsInt("mushaf") == 2)
			item3.setSelected(true);
		item3.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				Quran.setMushaf(2);
				UIDelegate.refreshVerse();
				UIDelegate.SectionPaneHook.refresh();
				if (QuranicTextList.getPreferred() < 0
						&& MainFrame.view_Windows.isSearchContainerMounted())
				{
					MainFrame.view_Windows.getSearchPanel().refreshResults();
				}
			}
		});

		item2.add(item3);
		bg.add(item3);

		popupMenu_Browser.add(item2);
	}

	private void refreshPopup()
	{
		if (!UIDelegate.BookmarkPaneHook.getBookmarkList().contains(
				UIDelegate.getDisplayedVerse()))
		{
			popupMenu_Browser.getComponent(3).setEnabled(true);
		}
		else
		{
			popupMenu_Browser.getComponent(3).setEnabled(false);
		}
		if (UIDelegate.getDisplayedVerse().getSimilarVerses() != null)
		{
			popupMenu_Browser.getComponent(4).setEnabled(true);
		}
		else
		{
			popupMenu_Browser.getComponent(4).setEnabled(false);
		}
		if (UIDelegate.isBrowserLocked()
				&& !RecitationController.getImam().isPaused())
		{
			popupMenu_Browser.getComponent(6).setEnabled(false);
		}
		else
		{
			popupMenu_Browser.getComponent(6).setEnabled(true);
		}
		if (UIDelegate.fontSize < 5)
		{
			popupMenu_Browser.getComponent(10).setEnabled(true);
		}
		else
		{
			popupMenu_Browser.getComponent(10).setEnabled(false);
		}
		if (UIDelegate.fontSize > 0)
		{
			popupMenu_Browser.getComponent(11).setEnabled(true);
		}
		else
		{
			popupMenu_Browser.getComponent(11).setEnabled(false);
		}
	}

	private void initListeners()
	{

		// table_BrowserPane.addMouseMotionListener(new MouseMotionListener()
		// {
		//
		// @Override
		// public void mouseMoved(MouseEvent e)
		// {
		// int index = table_BrowserPane.rowAtPoint(e.getPoint());
		// }
		//
		// @Override
		// public void mouseDragged(MouseEvent e)
		// {
		// }
		// });

		table_BrowserPane.addMouseListener(new MouseAdapter()
		{

			@Override
			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					mouseEvent = e;
					refreshPopup();
					popupMenu_Browser.show(e.getComponent(), e.getX(), e.getY());
				}

			}

			@Override
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					mouseEvent = e;
					refreshPopup();
					popupMenu_Browser.show(e.getComponent(), e.getX(), e.getY());
				}
			}

		});

		// table_BrowserPane.addMouseMotionListener(new MouseMotionAdapter() {
		//
		// @Override
		// public void mouseMoved(MouseEvent e) {
		// if (e.getButton() == MouseEvent.NOBUTTON) {
		// int mouseX;
		// int mouseY;
		// Component mouseComponent;
		// final Point mousePoint = e.getPoint();
		// mouseComponent = e.getComponent();
		// mouseX = e.getX();
		// mouseY = e.getY();
		// SwingUtilities.invokeLater(new Runnable() {
		// @Override
		// public void run() {
		// Point p = mousePoint;
		// int caret = viewToModel(p);
		// if (caret < 0)
		// popupMenu_WordByWord.setVisible(false);
		// else {
		// refreshWordByWordInfo(caret);
		// popupMenu_WordByWord
		// .show(mouseComponent, mouseX
		// - (4 * WordByWord
		// .getTranslation()
		// .length()), mouseY + 25);
		// }
		// }
		// });
		// }
		// }
		// });

		// addMouseListener(new MouseAdapter()
		// {
		// @Override
		// public void mouseExited(MouseEvent e) {
		// popupMenu_WordByWord.setVisible(false);
		// }
		// });

		addMouseWheelListener(new MouseWheelListener()
		{

			@Override
			public void mouseWheelMoved(MouseWheelEvent e)
			{
				int rotation = e.getWheelRotation();

				if (e.isControlDown())
				{
					setWheelScrollingEnabled(false);
					if (rotation < 0)
					{
						if (UIDelegate.fontSize < 5)
						{
							UIDelegate.fontSize++;
							UIDelegate.refreshVerse();
						}
						else
						{
							Toolkit.getDefaultToolkit().beep();
						}
					}
					else if (rotation > 0)
					{
						if (UIDelegate.fontSize > 0)
						{
							UIDelegate.fontSize--;
							UIDelegate.refreshVerse();
						}
						else
						{
							Toolkit.getDefaultToolkit().beep();
						}
					}

				}

			}
		});
	}

	private class TableListener implements TableModelListener {
		@Override
		public void tableChanged(TableModelEvent te)
		{
			tableValues = new String[QuranicTextList
					.getNumberOfDisplayedTexts(UIDelegate.getDisplayedVerse()) + 1];
			tableValues[0] = UIDelegate.getDisplayedVerse().getContent();
			for (int i = 1; i < tableValues.length; i++)
			{
				tableValues[i] = StringToolkit
						.indentParagraph(
								QuranicTextList
										.getText(
												QuranicTextList
														.getIndexByDisplayOrder(
																i - 1,
																UIDelegate
																		.getDisplayedVerse()))
										.getVerseContent(
												UIDelegate.getDisplayedVerse()),
								"     ");
			}
		}
	}

	public class TableModel extends AbstractTableModel {

		private static final long serialVersionUID = -4179998068419126729L;

		public TableModel()
		{
		}

		@Override
		public int getRowCount()
		{
			return tableValues.length;
		}

		@Override
		public int getColumnCount()
		{
			return 1;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex)
		{
			return tableValues[rowIndex];
		}

		@Override
		public Class<?> getColumnClass(int columnIndex)
		{
			return String.class;
		}
	}

	public class TableRenderer extends TextAreaRenderer {

		private final TitledBorder border = BorderFactory.createTitledBorder(
				BorderFactory.createEtchedBorder(EtchedBorder.LOWERED,
						Color.DARK_GRAY, Color.DARK_GRAY), "0", 0,
				TitledBorder.BELOW_TOP, FontLibrary.get(FontLibrary.DROID_SANS,
						Font.BOLD, 12), new Color(41, 97, 90));
		private final TitledBorder border2 = BorderFactory.createTitledBorder(
				BorderFactory.createEtchedBorder(EtchedBorder.LOWERED,
						Color.DARK_GRAY, Color.DARK_GRAY), "0", 0,
				TitledBorder.BELOW_TOP, FontLibrary.get(FontLibrary.DROID_SANS,
						Font.BOLD, 12), new Color(129, 16, 28));
		private final TitledBorder border3 = BorderFactory.createTitledBorder(
				BorderFactory.createEtchedBorder(EtchedBorder.RAISED,
						Color.DARK_GRAY, Color.DARK_GRAY), "", 0,
				TitledBorder.BELOW_TOP, FontLibrary.get(FontLibrary.DROID_SANS,
						Font.BOLD, 12), Color.white);

		public TableRenderer()
		{
			super();
		}

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object obj, boolean isSelected, boolean hasFocus, int row,
				int column)
		{
			adaptee.getTableCellRendererComponent(table, obj, isSelected,
					hasFocus, row, column);
			QuranicText qt = null;
			if (row == 0)
			{
				setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
			}
			else
			{
				qt = QuranicTextList.getText(QuranicTextList
						.getIndexByDisplayOrder(row - 1,
								UIDelegate.getDisplayedVerse()));
				if (qt.isRTL())
				{
					setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
				}
				else
				{
					setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
				}
			}
			if (row == 0)
			{
				setForeground(Color.white);
				setBackground(Color.DARK_GRAY);
			}
			else
			{
				setForeground(adaptee.getForeground());
				setBackground(adaptee.getBackground());
			}
			TitledBorder tb;
			if (row == 0) tb = border3;
			else
			{
				if ((row - 1) % 2 == 0) tb = border;
				else tb = border2;
				tb.setTitle(qt.getSpecifications());
				tb.setTitleJustification(qt.isRTL() ? Integer
						.valueOf(TitledBorder.RIGHT) : Integer
						.valueOf(TitledBorder.LEFT));
			}
			setBorder(tb);
			if (row == 0) setFont(FontLibrary.get(FontLibrary.SCHERAZADE,
					UIDelegate.getQuranFontSize()));
			else setFont(FontLibrary.get(FontLibrary.CODE2000,
					UIDelegate.getTextFontSize()));

			// if (refreshRequired != null) {
			// if (refreshRequired[row]) {
			// setText(adaptee.getText());
			// docs[row] = getDocument();
			// refreshRequired[row] = false;
			// } else {
			// if (docs[row] != null) {
			// setDocument(docs[row]);
			// }
			// }
			// }

			// if (pendingDocumentRefresh != null) {
			// if (pendingDocumentRefresh[row]) {
			// setDocument(docs[row].getDocument());
			// pendingDocumentRefresh[row] = false;
			// }
			// }

			if (!getText().equals(adaptee.getText()))
			{
				setText(adaptee.getText());
			}

			TableColumnModel columnModel = table.getColumnModel();
			setSize(columnModel.getColumn(column).getWidth(), 100000);
			int height_wanted = (int) getPreferredSize().getHeight();
			addSize(table, row, column, height_wanted);
			height_wanted = findTotalMaximumRowSize(table, row);
			if (height_wanted != table.getRowHeight(row))
			{
				table.setRowHeight(row, height_wanted);
			}
			return this;
		}

		@Override
		public void invalidate()
		{
		}

		@Override
		public void repaint()
		{
		}

	}
}
